package com.atgugu.springcloud.mygateway;

import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

@Component
public class MyGatewayFilterFactory extends AbstractGatewayFilterFactory<MyGatewayFilterFactory.Config > {

    public MyGatewayFilterFactory() {
        super(MyGatewayFilterFactory.Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                ServerHttpRequest request = exchange.getRequest();
                //请求中带有key（名字为：param的值），进入逻辑
                if (request.getQueryParams().containsKey(config.getParam())) {
                    //打印
                    request.getQueryParams().get(config.getParam()).forEach((value) -> {
                        System.out.println("获取到的key为" + config.param);
                        System.out.println("获取到的value为" + value);
                    });
                    //放行
                    return chain.filter(exchange);
                } else {
                    //设置异常状态码
                    exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
                    return exchange.getResponse().setComplete();
                }
            }
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return List.of("param");
    }

    @Setter
    @Getter
    public static class Config {
        private String param;//设定一个参数，该参数的值必须作为key传递才能访问
    }
}
